package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.globalException.LeaseException;
import com.atguigu.lease.common.properties.JwtProperties;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private JwtProperties jwtProperties;

    @Override
    //app端登录
    public String login(LoginVo loginVo) {
        //1.判断是否有验证码
        if(loginVo.getCode() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.判断验证码是否过期
        String code = redisTemplate.opsForValue().get(loginVo.getPhone()).toString();
        if(code == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }

        //3.判断验证码是否正确
        if(!code.contains(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //4.根据邮箱查找用户，如果存在则判断账号状态，不存在则创建新用户
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if(userInfo == null){
            //创建新用户
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户-"+ UUID.randomUUID());
            userInfoService.save(userInfo);
        }
        if(userInfo.getStatus() == BaseStatus.DISABLE){
            //账号被禁用
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        Map<String, Object> claims = new HashMap<>();
        claims.put("appUserId", userInfo.getId());
        //创建jwt令牌
        String jwt = JwtUtil.createJwt(jwtProperties.getAppSecretKey(), jwtProperties.getAppTtl(), claims);
        return jwt;
    }
}
